from django.shortcuts import render
from django.views.decorators.cache import cache_page
from rest_framework import viewsets, status, generics
from rest_framework.generics import ListCreateAPIView
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.views import APIView

from api.ownserializers import ScenicSerializer, ScenicdetailSerializer
from common.models import TbScenic, TbCity


class PaginationSource(PageNumberPagination):
    """
    分页
    """
    page_size = 3
    page_query_param = 'page'
    page_size_query_param = 'size'


class ScenicSourceTop(viewsets.ReadOnlyModelViewSet):
    # 查询景点的数据
    queryset = TbScenic.objects.all().order_by('-id')[:5]
    # 序列化
    serializer_class = ScenicSerializer


class SceniclistView(ListCreateAPIView):
    """
    城市景点列表
    """
    queryset = TbScenic.objects.all()
    serializer_class = ScenicSerializer

    def get(self, request, city_id, *args, **kwargs):
        try:
            query_set = TbScenic.objects.filter(city_id=city_id)
            pager = PaginationSource()
            paged_query_set = pager.paginate_queryset(queryset=query_set, request=request, view=self)
            return pager.get_paginated_response(
                ScenicSerializer(paged_query_set, many=True).data)

        except TbCity.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)


class ScenicSourceDetail(APIView):
    """
    景点详情
    """
    def get(self, request, pk, *args, **kwargs):
        try:
            serializer = ScenicdetailSerializer(TbScenic.objects.get(pk=pk))
            return Response(serializer.data)
        except TbScenic.DoesNotExist:
            return Response(status=status.HTTP_404_NOT_FOUND)

